<template>
  <div>
    <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle">
      <BasicForm @register="registerForm" />

      <template #footer>
        <Space :size="8">
          <a-button @click="handleClose"> 取消 </a-button>
          <a-button type="success" @click="handleSave"> 保存 </a-button>
          <a-button type="primary" @click="handleSubmit"> 提交 </a-button>
        </Space>
      </template>
    </BasicModal>
    <ImagePreview :imageList="imgList" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { formSchemaCommercial, formSchemaResident } from './editPlace.data';
  import { Tabs, Space, Upload, Divider, Tag, Avatar, Tooltip } from 'ant-design-vue';
  import {
    editPoliceCommercialPlaceInfo,
    editPoliceResidentPlaceInfo,
    submitResidentPlace,
    submitCommercialPlace,
  } from '/@/api/demo/system';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import type { UploadProps } from 'ant-design-vue';
  import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
  import { useGlobSetting } from '/@/hooks/setting';
  import { FileItem } from '/@/components/Upload/src/typing';
  const globSetting = useGlobSetting();
  import { uploadImage } from '/@/api/sys/upload';
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();
  const tk = userStore.getToken;

  export default defineComponent({
    name: 'AddPlaceModal',
    components: { BasicModal, BasicForm, Space, Upload, PlusOutlined, ImagePreview },
    props: {
      placeType: {
        type: Number,
        default: 0,
      },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const isUpdate = ref(true);
      const editId = ref('');
      const editHId = ref('');
      const editRecord = ref({});
      const fileList = ref<UploadProps['fileList']>([]);
      const imgList: string[] = [];

      let formschemas: FormSchema[] = [];
      if (0 == props.placeType) {
        formschemas = formSchemaResident;
      } else {
        formschemas = formSchemaCommercial;
      }

      const [
        registerForm,
        { resetFields, setFieldsValue, updateSchema, validate, getFieldsValue, clearValidate },
      ] = useForm({
        labelWidth: '50%',
        labelAlign: 'left',
        schemas: formschemas,
        showActionButtonGroup: false,
      });

      function adjustValues(formschemas: FormSchema[], record: any) {
        formschemas.forEach((ele) => {
          if (ele.field.startsWith('_')) {
            const val = record[ele.field.substring(1)];
            if (val) {
              const valObj = JSON.parse(val);
              if (valObj.list) {
                const valObj2: string[] = [];
                valObj.list.forEach((element) => {
                  if (element.checked) {
                    valObj2.push(element.title);
                  }
                });
                if ('CheckboxGroup' == ele.component) {
                  record[ele.field] = valObj2;
                } else if ('RadioGroup' == ele.component) {
                  if (valObj2.length > 0) {
                    record[ele.field] = valObj2[valObj2.length - 1];
                  }
                } else if ('Select' == ele.component) {
                  if (valObj2.length > 0) {
                    record[ele.field] = valObj2[valObj2.length - 1];
                  }
                }
              }
            }
          }
        });

        if (record['integrationInspectorSign']) {
          fileList.value = [];
          fileList.value.push({
            uid: record['integrationInspectorSign'],
            name: record['integrationInspectorSign'],
            url: `${globSetting.apiBaseUrl}/api/v1/images/${record['integrationInspectorSign']}?access_token=${tk}`,
          });
        }

        return record;
      }

      async function uploadApiByItem(item: FileItem) {
        console.log(item);
        if (item.originFileObj) {
          const { data } = await uploadImage(item.originFileObj);
          if (data.succ) return data.data;
        }

        return null;
      }

      async function rebuildValues(formschemas: FormSchema[], record: any) {
        formschemas.forEach((ele) => {
          if (ele.field.startsWith('_')) {
            const val = record[ele.field];
            const eleComponentProps: any = ele.componentProps;
            if (val) {
              if ('CheckboxGroup' == ele.component) {
                const valObj2: any[] = [];
                eleComponentProps.options.forEach((element) => {
                  valObj2.push({
                    checked: val.includes(element.value),
                    code: '',
                    title: element.value,
                  });
                });
                record[ele.field.substring(1)] = JSON.stringify({ list: valObj2 });
              } else if ('RadioGroup' == ele.component) {
                const valObj2: any[] = [];
                eleComponentProps.options.forEach((element) => {
                  valObj2.push({
                    checked: val == element.value,
                    code: '',
                    title: element.value,
                  });
                });
                record[ele.field.substring(1)] = JSON.stringify({ list: valObj2 });
              } else if ('Select' == ele.component) {
                const valObj2: any[] = [];
                eleComponentProps.options.forEach((element) => {
                  valObj2.push({
                    checked: val == element.value,
                    code: '',
                    title: element.value,
                  });
                });
                record[ele.field.substring(1)] = JSON.stringify({ list: valObj2 });
              }
            }
          }
        });

        record['chongDianVillage'] = record['chongDianVillage'] || false;

        const data = await Promise.all(
          fileList.value.map((item) => {
            return uploadApiByItem(item);
          }),
        );

        if (data.length > 0 && data[0]) {
          record['integrationInspectorSign'] = data[0];
        }
        return record;
      }

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false, destroyOnClose: true });
        fileList.value = [];
        isUpdate.value = !!data?.isUpdate;
        editId.value = data.record.id;
        editHId.value = data.record.houseId;
        editRecord.value = data.record;
        const adj = adjustValues(formschemas, data.record);
        if (unref(isUpdate)) {
          setFieldsValue({
            ...adj,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '场所隐患信息录入' : '场所隐患信息录入'));

      function handleClose() {
        closeModal();
      }

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          values.id = editId.value;
          values.houseId = editHId.value;
          values.location = editRecord.value.location;
          await rebuildValues(formschemas, values);
          // TODO custom api
          if (unref(isUpdate)) {
            if (0 == props.placeType) {
              await editPoliceResidentPlaceInfo(values);
              await submitResidentPlace(values);
            } else {
              await editPoliceCommercialPlaceInfo(values);
              await submitCommercialPlace(values);
            }
          } else {
            //await addPlaceList(values);
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      async function handleSave() {
        try {
          await clearValidate();
          const values = await getFieldsValue();
          setModalProps({ confirmLoading: true });
          values.id = editId.value;
          values.houseId = editHId.value;
          values.location = editRecord.value.location;
          await rebuildValues(formschemas, values);
          // TODO custom api
          if (unref(isUpdate)) {
            if (0 == props.placeType) {
              await editPoliceResidentPlaceInfo(values);
            } else {
              await editPoliceCommercialPlaceInfo(values);
            }
          } else {
            //await addPlaceList(values);
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function getBase64(file: File) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => resolve(reader.result);
          reader.onerror = (error) => reject(error);
        });
      }

      const handlePreview = async (file: UploadProps['fileList'][number]) => {
        if (!file.url && !file.preview) {
          file.preview = (await getBase64(file.originFileObj)) as string;
        }
        const onImgLoad = ({ index, url, dom }) => {
          console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
        };
        imgList.length = 0;
        imgList.push(file.url || file.preview);
        // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
        createImgPreview({ imageList: imgList, defaultWidth: 700, rememberState: true, onImgLoad });
      };

      const handleRemove: UploadProps['onRemove'] = (file) => {
        const index = fileList.value.indexOf(file);
        const newFileList = fileList.value.slice();
        newFileList.splice(index, 1);
        fileList.value = newFileList;
      };

      const beforeUpload: UploadProps['beforeUpload'] = (file) => {
        fileList.value = [...fileList.value, file];
        return false;
      };

      return {
        imgList,
        handleRemove,
        beforeUpload,
        registerModal,
        fileList,
        handlePreview,
        registerForm,
        getTitle,
        handleSubmit,
        handleSave,
        handleClose,
      };
    },
  });
</script>
